// 秀岳个人申请的（web端）
// export const AMAPKEY = '72e3718b3131b98df66cf773f490f10c'
// 某新申请的 服务端
export const SERVEAMAPKEY = '2e7926e552133d278d15dc8d6fdf1e6e'
// 某新申请的 WEB端
export const AMAPKEY = 'f91b780587e29607b67f15fcf4ef0965'


var oldPostion = null
var oldPostionTime = false
var Toast = {
  clear: () => void 0
}
//加载地图
export const loadMap = (key, plugins, v = '1.4.13') => {
  return new Promise(function (resolve, reject) {
    if (typeof AMap !== 'undefined') {
      // eslint-disable-next-line no-undef
      resolve(AMap)
      return true
    }
    window.onCallback = function () {
      // eslint-disable-next-line no-undef
      resolve(AMap)
    }
    let script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = `https://webapi.amap.com/maps?v=${v}&key=${key}&plugin=${plugins}&callback=onCallback`
    script.onerror = reject
    document.head.appendChild(script)
  })
}

function dataURItoBlob(byteString) {
  var mimeString = 'application/javascript'
  var arrayBuffer = new ArrayBuffer(byteString.length) //创建缓冲数组
  var intArray = new Uint8Array(arrayBuffer) //创建视图

  for (var i = 0; i < byteString.length; i++) {
      intArray[i] = byteString.charCodeAt(i)
  }
  return new Blob([intArray], {type: mimeString})
}
export const getBlobUrl = (url) => new Promise((resolve, reject) => {
  const xhr = new XMLHttpRequest()
  xhr.open('GET', url, true)
  xhr.onload = function () {
    if (this.status === 200) {
      let text = this.response
      text = 'console.log(location,navigator);' + text
      const blob = dataURItoBlob(text)
      const b = URL.createObjectURL(blob)
      resolve(b)
    }
  }
  xhr.send()
})

export const asyncLoadAMAP = () => {
  const Toast =TESTVUE.$toast.loading({
    duration: 0,       // 持续展示 toast
    // forbidClick: true, // 禁用背景点击
    loadingType: 'spinner',
    // mask: true,
    message: ''
  })
  var scriptID = 'global_div_head_map_amp_ID_1561083039276'
  if (document.getElementById(scriptID)) {
    console.log(document.getElementById(scriptID))
    try {
      document.head.removeChild(document.getElementById(scriptID))      
    } catch (error) {
      console.log(error)
    }
  }
  let loadAmapJs = async () => {
    console.log('加载中。。', window.AMap, window.map_callback)
    if (window.AMap) {
      Toast.clear()
      window.map_callback && window.map_callback()
      return
    }
    var scriptUrl = `https://webapi.amap.com/maps?v=1.4.13&key=${AMAPKEY}&plugin=&callback=map_callback`
    var script = document.createElement('script')
    script.id = scriptID
    script.src = scriptUrl
    window.amapUIJs = '1'
    script.onload = () => {
      Toast.clear()
    }
    // let scriptBlobUrl = await getBlobUrl(scriptUrl)
    // var worker = new Worker(scriptUrl)
    // var worker = new Worker(scriptBlobUrl)
    // console.log(worker)
    setTimeout(() => {
      document.head.appendChild(script)
    }, 0)
  }
  if (!window.amapUIJs) {
    console.log('加载amap script')
    var amapUIJs = document.createElement('script')
    amapUIJs.src = 'https://webapi.amap.com/ui/1.0/main-async.js'
    document.head.appendChild(amapUIJs)
    amapUIJs.onload = loadAmapJs
  } else {
    loadAmapJs()
  }
}
const GetWebsite = () => new Promise((resolve, reject) => {
  if(!window.AMap){
    console.log('未开启地图')
    return
  }
  if(oldPostionTime && (+new Date()) - oldPostionTime < (1e3 * 30)){
    resolve(oldPostion)
    return
  }
  // const Toast =TESTVUE.$toast.loading({
  //   duration: 0,       // 持续展示 toast
  //   // forbidClick: true, // 禁用背景点击
  //   loadingType: 'spinner',
  //   // mask: true,
  //   message: ''
  // })
  var geolocation
  var mapObj = new AMap.Map('iCenter')
  mapObj.plugin('AMap.Geolocation', function () {
      geolocation = new AMap.Geolocation({
          enableHighAccuracy: true,//是否使用高精度定位，默认:true
          timeout: 10000,          //超过10秒后停止定位，默认：无穷大
          maximumAge: 6e4,           //定位结果缓存0毫秒，默认：0
      })
      mapObj.addControl(geolocation)
      geolocation.getCurrentPosition()
      AMap.event.addListener(geolocation, 'complete', (e) => {
          console.log(e.position)
          let response = [e.position.lng, e.position.lat, '南山区']
          oldPostion = response
          oldPostionTime = +new Date()
          resolve(response)
          Toast.clear()
      })
      //返回定位信息
      AMap.event.addListener(geolocation, 'error', (e) => {
          if(e.message.includes('Geolocation permission denied')){
            reject('请打开GPS')
            return
          }
          if(e.message.includes('Get geolocation failed')){
            reject('海外，海上暂无法定位到')
            return
          }
          if(e.message.includes('Get geolocation time out')){
            reject('定位超时，设备不稳定')
            return
          }
          if(e.message.includes('Browser not Support html5 geolocation')){
            reject('浏览器版本过低，无法定位')
            return
          }
          if(e.message.includes('Get ipLocation failed')){
            reject('偏远位置无法定位')
            return
          }
          reject('定位失败')
          Toast.clear()
          console.log(e)
          // alert(JSON.stringify(e))
      })      //返回定位出错信息
  })
})
export const Getsite = () => {
  if(!window.AMap){
    console.log('未开启地图')
    return
  }
  if(!Boolean(window.plus)){
    return GetWebsite()
  }
  return new Promise((resolve, reject) => {
    if(oldPostionTime && (+new Date()) - oldPostionTime < (1e3 * 30)){
      resolve(oldPostion)
      return
    }
    // const Toast =TESTVUE.$toast.loading({
    //   duration: 0,       // 持续展示 toast
    //   // forbidClick: true, // 禁用背景点击
    //   loadingType: 'spinner',
    //   // mask: true,
    //   message: ''
    // })
    let success = (position) => {
      console.log('原生定位成功.')
      
      // try {
      //   let response = [position.coords.longitude, position.coords.latitude, position.address.district]
      //   oldPostion = response
      //   oldPostionTime = +new Date()
      //   resolve(response)
      //   Toast.clear() 
      // } catch (error) {
      //   console.log(error)
      //   reject('定位异常')
      // }
      console.log(JSON.stringify(position))
      // console.log(JSON.stringify(position.coords))
      AMap.convertFrom([position.coords.longitude, position.coords.latitude], 'gps', function (status, result) {
        console.log('result')
        console.log('转高德地图中')
        console.log(result)
        if (result.info === 'ok') {
          var lnglats = result.locations; // Array.<LngLat>
          console.log(JSON.stringify(lnglats))
          console.log('地址转换中')
          AMap.plugin('AMap.Geocoder', () => {
            new AMap.Geocoder({
              // city: "010",
              // radius: 1000 //范围，默认：500 
            })
            .getAddress([lnglats[0].lng, lnglats[0].lat], (addressstatus, addressResult) => {
                console.log('经纬度转地址成功', addressstatus)
                if (addressstatus === 'complete' && addressResult.regeocode) {
                  console.log(JSON.stringify(addressResult.regeocode.addressComponent))
                    var district = addressResult.regeocode.addressComponent.district
                    console.log(district)
                    try {
                      let response = [lnglats[0].lng, lnglats[0].lat, district]
                      oldPostion = response
                      oldPostionTime = +new Date()
                      resolve(response)
                      Toast.clear() 
                    } catch (error) {
                      console.log(error)
                      reject('定位异常')
                    }
                }else{
                  reject('定位异常')
                }
            })
          })
          // 处理地址完成
        }
      })
    }
    let onerror = (errorObj) => {
      console.log('原生定位失败')
      console.log(errorObj, errorObj.code)
      reject(errorObj.message)
      Toast.clear()
    }
    let options = {
      enableHighAccuracy: true,
      timeout: 1e4,
      maximumAge: 10,
      provider: 'system',
      // coordsType: 'bd09ll'
    }
    plus.geolocation.getCurrentPosition(success, onerror, options)

    // // 获取GPS
    // plus.geolocation.getCurrentPosition((position) => {
    //   console.log('原生GPS定位成功')
    //   console.log(JSON.stringify(position.coords))
    // }, onerror, {
    //   enableHighAccuracy: true,
    //   timeout: 1e4,
    //   maximumAge: 10,
    //   provider: 'system'
    // })
  })
}